import {
  Button,
  Divider,
  message,
  Descriptions,
  Popconfirm,
  Select,
  Badge,
  Input,
  Upload,
  Table
} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import {DownloadOutlined, UploadOutlined} from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import defaultSetting from '@/../config/defaultSettings';
import {
  queryRule,
  examineRule,
  examineRuleByWechat,
  removeRule,
  getRecord,
  getOrder,
  getOrderDetails,
  storeList,
  exportRefund,
  revokeRule,
  getMemberActivityList
} from './service';
import styles from '../../../global.less';
import OrderCommon from '@/pages/OrderCommon';
import {money_trans, saveFileAs} from '@/utils/utils';
import moment from 'moment';
import {getPayOrder} from "@/pages/VipManagement/IntegralDay/service";
import Access from '@/components/Access/Access';

const handleExamine = async (fields, actionRef, handleModalVisible) => {
  const hide = message.loading('正在审核');

  try {
    await examineRule(fields);
    hide();
    message.success('审核成功');
    handleModalVisible(false);
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('审核请重试！');
    return false;
  }
};
const handleExamineByWechat = async (fields, actionRef, handleModalVisible) => {
  const hide = message.loading('正在审核');

  try {
    await examineRuleByWechat(fields);
    hide();
    message.success('审核成功');
    handleModalVisible(false);
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('审核请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows, actionRef) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule(selectedRows);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const handleRevoke = async (selectedRows, actionRef) => {
  const hide = message.loading('正在撤销');
  if (!selectedRows) return true;

  try {
    await revokeRule(selectedRows);
    hide();
    message.success('撤销成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('撤销失败，请重试');
    return false;
  }
};
const TableList = (props) => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [uploadLoading, setUploadLoading] = useState(false);
  const [remark, setRemark] = useState();
  const actionRef = useRef();

  const [order, setOrder] = useState();
  const [memberActivity, setMemberActivity] = useState();
  const [orderState, setOrderState] = useState();
  const [payOrderValues, setPayOrderValues] = useState({});
  const [memberActivityList, setMemberActivityList] = useState([]);
  const [details, setDetails] = useState();
  const [refundOrder, setRefundOrder] = useState({});
  const [count, setCount] = useState();
  const [storeArray, setStoreArray] = useState([]);
  const [outModal, handleOutModal] = useState(false);
  const [exportRecords, setExportRecords] = useState(false);
  const getStore = () => {
    storeList()
      .then((res) => {
        const { code } = res;
        code === 0 ? setStoreArray(res.data) : message.info(res.message);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const handleRecord = (payload) => {
    getRecord(payload).then((res) => {
      const { code, data } = res;
      code === 0 ? (handleModalVisible(true), setRefundOrder(data)) : null;
    });
  };
  const handleRemark = (e) => {
    setRemark(e.target.value);
  };
  const handlePass = () => {
    const params = {
      id: refundOrder.id,
      reason: remark,
      status: 2,
    };
    if (refundOrder.payType == 9){
      handleExamineByWechat(params, actionRef, handleModalVisible);
    }else{
      handleExamine(params, actionRef, handleModalVisible);
    }
  };
  const handleFull = () => {
    const params = {
      id: refundOrder.id,
      reason: remark,
      status: 3,
    };
    if (refundOrder.payType == 9){
      handleExamineByWechat(params, actionRef, handleModalVisible);
    }else{
      handleExamine(params, actionRef, handleModalVisible);
    }
  };
  const handleOrder = (payload) => {
    getOrder({ number: payload })
      .then((res) => {
        const { code } = res;
        if (code === 0) {
          const {
            data: { list },
          } = res;
          handleDetails_order(list[0].id);
          setDetails(list[0]);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const handleDetails_order = (payload) => {
    getOrderDetails(payload)
      .then((res) => {
        const { code } = res;
        code === 0 ? (setPayOrderValues(res.data), setOrderState(true)) : null;
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const uploadOnChange = (info) => {
    setUploadLoading(true);
    if (info.file.status === 'done') {
      setUploadLoading(false);
      const {
        file: {
          response: { code },
        },
      } = info;
      if (code == 0) {
        actionRef.current.reload();
        message.success('导入成功');
      } else {
        message.error('导入失败请重试！');
      }
    } else {
      // message.error('导入失败请重试！');
    }
  };
  const handlePay = (params) => {
    getPayOrder(params).then((res) => {
      const {code, data} = res;
      code === 0 ? (setPayOrderValues(data), setOrder(true)) : null;
    });
  };
  const handleMemberActivityList = (params) => {
    getMemberActivityList(params).then((res) => {
      const {code, data} = res;
      code === 0 && data.length>0 ? (setMemberActivityList(data), setMemberActivity(true)) : null;
    });
  };
  useEffect(() => {
    getStore();
  }, []);
  const activityColumns = [
    {
      title: '订单单据',
      dataIndex: 'orderNumber',
      hideInForm: true,
      hideInSearch: true,
      render: (_, record) => {
        return <a
          onClick={() => {
            handlePay(record.orderId);
            setOrder(true);
          }}
        >
          {_}
        </a>;
      }
    },
    {
      title: '活动名',
      dataIndex: 'activityName',
    },
    {
      title: '赠品名',
      dataIndex: 'activityDelivName',
    },
    {
      title: '赠送数量',
      dataIndex: 'activityDelivCount',
    },
    {
      title: '领取数量',
      dataIndex: 'count',
    },
    {
      title: '销售人员',
      dataIndex: 'sellerName',
    },
    {
      title: '下单时间',
      dataIndex: 'payTime',
      render: (_, record) => {
        return new Date(record.payTime).toLocaleDateString();
      },
    },
  ];
  const record_columns = [
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      hideInForm: true,
    },
    {
      title: '商品品项',
      dataIndex: 'goodsItemName',
      hideInForm: true,
    },
    {
      title: '单价',
      dataIndex: 'price',
      hideInForm: true,
      render: (dom) => {
        return money_trans(dom);
      },
    },
    {
      title: '退货数量',
      dataIndex: 'count',
      hideInForm: true,
    },
    {
      title: '总价',
      dataIndex: 'amount',
      hideInForm: true,
      render: (dom) => {
        return money_trans(dom);
      },
    },
  ];
  const columns = [
    {
      title: '会员卡号',
      dataIndex: 'memberNumber',
      hideInForm: true,
      width: 80,
      render: (_, record) => {
        return (record.type === 4)?(
          <a
            onClick={() => {
              handleMemberActivityList(record.memberId);
              setMemberActivity(true);
            }}
          >
            {_}
          </a>
        ):_;
      }
    },
    {
      title: '订单单据',
      dataIndex: 'number',
      hideInForm: true,
      hideInSearch: true,
      render: (_, record) => {
        return (record.type === 1|| record.type === 2)?(
          <a
            onClick={() => {
              handlePay(record.orderId);
              setOrder(true);
            }}
          >
            {_}
          </a>
          ):_
         ;
      }
    },
    {
      title: '单据号',
      dataIndex: 'orderNumber',
      hideInForm: true,
    },
    {
      title: '开卡店铺',
      dataIndex: 'openStoreName',
      hideInForm: true,
      hideInSearch: true,
      width: 100,
    },
    {
      title: '会员名称',
      dataIndex: 'memberName',
      hideInForm: true,
      width: 80,
    },
    {
      title: '联系电话',
      dataIndex: 'memberMobile',
      hideInForm: true,
      width: 80,
    },

    {
      title: '退款店铺',
      dataIndex: 'storeName',
      hideInForm: true,
      hideInSearch: true,
      width: 100,
    },
    {
      title: '退款店铺',
      dataIndex: 'storeIdParam',
      hideInForm: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select
            placeholder="请选择店铺"
            showSearch
            allowClear
            filterOption={(input, option) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {storeArray.map((item_, index) => {
              return (
                <Select.Option value={item_.id} key={item_.id}>
                  {item_.name}
                </Select.Option>
              );
            })}
          </Select>
        );
      },
    },

    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      width: 100,

      valueEnum: {
        0: {
          text: '申请中',
          status: 'Processing',
        },
        1: {
          text: '退款处理中',
          status: 'Processing',
        },
        4: {
          text: '取消申请',
          status: 'Default',
        },
        2: {
          text: '申请通过',
          status: 'Success',
        },
        3: {
          text: '拒绝申请',
          status: 'Error',
        },
      },
    },
    {
      title: '退款总金额',
      dataIndex: 'amount',
      hideInSearch: true,
      width: 90,

      render: (dom, entity) => {
        return money_trans(dom, true);
      },
    },
    {
      title: '退款总积分',
      hideInSearch: true,
      dataIndex: 'integral',
      width: 90,
      render: (dom, entity) => {
        return <span style={{ fontWeight: 'bolder',color:'blue' }}>{dom}</span>;
      },
    },
    {
      title: '支付方式',
      dataIndex: 'payType',
      width: 100,
      valueEnum: {
        1: {
          text: '现金支付',
          status: 'Processing',
        },
        2: {
          text: '刷卡支付',
          status: 'Success',
        },
        3: {
          text: '扫码支付',
          status: 'Error',
        },
        4: {
          text: '余额支付',
          status: 'Error',
        },
        5: {
          text: '积分支付',
          status: 'Error',
        },
        9: {
          text: '微信支付',
          status: 'Success',
        },
      },
      render: (dom, entity) => {
        return <span style={{ fontWeight: 'bolder', color: 'red' }}>{dom}</span>;
      },
    },
    {
      title: '审核时间',
      dataIndex: 'auditTime',
      valueType: 'dateTime',
      hideInForm: true,
      width: 80,

      hideInSearch: true,
      render: (_, record) => {
        if (record.auditTime !== null) {
          return new Date(record.auditTime).toLocaleString();
        } else {
          return '-';
        }
      },
    },
    {
      title: '审核人',
      dataIndex: 'auditor',
      width: 80,
      hideInSearch: true,
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '下单时间',
      dataIndex: 'createTime',
      width: 100,
      hideInSearch: true,
      render: (dom) => {
        return <div>{new Date(dom).toLocaleString()}</div>;
      },
    },
    {
      title: '说明',
      dataIndex: 'reason',
      hideInForm: true,
      width: 180,
      hideInSearch: true,
    },
    {
      title: '审核时间',
      dataIndex: 'created_at',
      hideInTable: true,
      valueType: 'date',
      width: 80,
      hideInSearch: true,
    },

    {
      title: '退款时间',
      dataIndex: 'createTime',
      hideInTable: true,
      width: 80,
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            startCreateTime: value[0],
            endCreateTime: value[1],
          };
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 100,
      render: (_, record) => {
        return (
          <>
            <Access accessKey={"@approveRefund"}>
              <a
                style={{
                  display: record.status == 0 ? '' : 'none',
                }}
                onClick={() => {
                  handleRecord(record.id);
                }}
              >
                审核
              </a>
              <Divider
                style={{
                  display: record.status == 0 ? '' : 'none',
                }}
                type="vertical"
              />
            </Access>
            <Access accessKey={"@deleteRefund"}>
              <Popconfirm
                placement="top"
                title="确定要删除吗?"
                onConfirm={() => {
                  handleRemove(record.id, actionRef);
                }}
                okText="确定"
                cancelText="取消"
              >
                <a>删除</a>
              </Popconfirm>
              <Divider
                type="vertical"
              />
            </Access>
            <Access accessKey={"@revokeRefund"}>
              <span
                style={{display: (record.status === 2 && (record.type === 4 || record.type === 5)) ? '' : 'none'}}
              >
              <Popconfirm
                placement="top"
                title="确定要撤回审批吗?"
                onConfirm={() => {
                  handleRevoke(record.id, actionRef);
                }}
                okText="确定"
                cancelText="取消"
              >
                <a>撤回</a>
              </Popconfirm>
            </span>
            </Access>
          </>
        );
      },
    },
  ];
  const outColumns = [
    {
      title: '会员卡号',
      dataIndex: 'memberNumber',
      valueType: 'text',
    },
    {
      title: '退款状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '申请中',
          status: 'Processing',
        },
        4: {
          text: '取消申请',
          status: 'Default',
        },
        2: {
          text: '申请通过',
          status: 'Success',
        },
        3: {
          text: '拒绝申请',
          status: 'Error',
        },
      },
    },
    {
      title: '退款时间',
      dataIndex: 'createTime',
      valueType: 'dateRange',
      render: (_, record) => {
        if (record.createTime) {
          return new Date(record.createTime).toLocaleString();
        } else {
          return '-';
        }
      },
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '退款时间为必选项',
          },
        ],
      },
    },
    {
      title: '退款店铺',
      dataIndex: 'storeId',
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择退款店铺" allowClear>
            {storeArray.map((item_, index) => {
              return (
                <Select.Option value={item_.id} key={index}>
                  {item_.name}
                </Select.Option>
              );
            })}
          </Select>
        );
      },
    },
  ];
  const BottomFooter = (
    <div className={styles.footer_btn}>
      <Button danger type="primary" onClick={handleFull}>
        拒绝
      </Button>
      <Button type="primary" onClick={handlePass}>
        通过
      </Button>
    </div>
  );
  return (
    <PageContainer>
      <ProTable
        headerTitle="退款记录"
        actionRef={actionRef}
        rowKey="id"
        bordered
        scroll={{ x: 1200 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => {
          return (
            <div>
              <Access accessKey={"@uploadOldRefundList"}>
                <Upload
                  name="file"
                  action={() => {
                    return `${defaultSetting.baseUrl}member/recordRefund/excel`;
                  }}
                  listType="picture"
                  showUploadList={false}
                  maxCount={1}
                  onChange={uploadOnChange}
                  headers={{ token: sessionStorage.getItem('token'), type: 'ADMIN' }}
                >
                  <Button type="primary" loading={uploadLoading} icon={<UploadOutlined />}>
                    导入一卡易记录
                  </Button>
                </Upload>

              </Access>

              {"  "}
              <Access accessKey={"@downloadRefundList"}>
                <Button
                  loading={exportRecords}
                  onClick={() => {
                    handleOutModal(true);
                    setExportRecords(true);
                  }}
                  type="primary"
                  danger
                  icon={<DownloadOutlined/>}
                >
                  导出申请记录
                </Button>
              </Access>

            </div>
          );
        }}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(payload) => {
          const { list, total } = payload;
          setCount(total);
          return list;
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
      />

      <CreateForm
        title={'导出信息'}
        width={800}
        btn_view={null}
        onCancel={() => handleOutModal(false)}
        modalVisible={outModal}
      >
        <ProTable
          className={styles.formModal}
          footer={null}
          onSubmit={(value) => {
            handleOutModal(false);
            exportRefund(value).then((res) => {
              if (res) {
                saveFileAs(res, '退款');
              }
              setExportRecords(false);
            });
          }}
          rowKey="id"
          bordered
          type="form"
          columns={outColumns}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
        />
      </CreateForm>
      <CreateForm
        width={1000}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        btn_view={BottomFooter}
      >
        <div>
          <Divider orientation="left">退款详情</Divider>
          <Descriptions>
            <Descriptions.Item label="会员名称">
              {refundOrder ? refundOrder.memberName : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="会员卡号">
              {refundOrder ? refundOrder.memberNumber : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="会员手机号">
              {refundOrder ? refundOrder.memberMobile : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="单据号">
              {refundOrder ? refundOrder.number : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="订单单号">
              <a
                onClick={() => {
                  return handleOrder(refundOrder.orderNumber);
                }}
              >
                {refundOrder ? refundOrder.orderNumber : '暂无'}
              </a>
            </Descriptions.Item>

            <Descriptions.Item label="支付状态">
              {(() => {
                switch (refundOrder ? refundOrder.status : null) {
                  case 0:
                    return <Badge status="processing" text="申请中" />;
                  case 1:
                    return <Badge status="success" text="申请通过" />;
                  case 2:
                    return <Badge status="error" text="申请拒绝" />;
                  case 3:
                    return <Badge status="default" text="取消申请" />;
                  default:
                    break;
                }
              })()}
            </Descriptions.Item>
            <Descriptions.Item label="支付方式">
              {(() => {
                switch (refundOrder ? refundOrder.payType : null) {
                  case 1:
                    return (
                      <Badge style={{ fontWeight: 'bolder' }} status="processing" text="现金支付" />
                    );
                  case 3:
                    return (
                      <Badge style={{ fontWeight: 'bolder' }} status="success" text="扫码支付" />
                    );
                  case 4:
                    return (
                      <Badge style={{ fontWeight: 'bolder' }} status="error" text="余额支付" />
                    );
                  case 5:
                    return (
                      <Badge style={{ fontWeight: 'bolder' }} status="default" text="积分支付" />
                    );
                  case 9:
                    return (
                      <Badge style={{ fontWeight: 'bolder' }} status="success" text="微信支付" />
                    );
                  default:
                    break;
                }
              })()}
            </Descriptions.Item>
            <Descriptions.Item label="退款类型">
              {(() => {
                switch (refundOrder ? refundOrder.type : null) {
                  case 0:
                    return <Badge status="processing" text="退货退款" />;
                  case 2:
                    return <Badge status="processing" text="仅退款" />;
                  default:
                    break;
                }
              })()}
            </Descriptions.Item>
            <Descriptions.Item label="退款总金额">
              {refundOrder ? money_trans(refundOrder.amount) : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="订单时间">
              {refundOrder.createTime ? new Date(refundOrder.createTime).toLocaleString() : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="审核时间">
              {refundOrder.auditTime ? new Date(refundOrder.auditTime).toLocaleString() : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="退款说明">
              <div
                dangerouslySetInnerHTML={{ __html: refundOrder ? refundOrder.reason : '暂无' }}
                style={{ maxHeight: 66, overflowY: 'auto', width: 200 }}
              ></div>
            </Descriptions.Item>
            <Descriptions.Item label="店铺名">
              {refundOrder ? refundOrder.storeName : '暂无'}
            </Descriptions.Item>
          </Descriptions>
          {/* <Divider orientation="left">退款图片</Divider>
          {refundOrder && refundOrder.imgList ? (
            refundOrder.imgList.map((item, index) => {
              return (
                <Descriptions.Item>
                  <Image src={item.url} />
                </Descriptions.Item>
              );
            })
          ) : (
            <Descriptions.Item>暂无</Descriptions.Item>
          )}

          <Divider orientation="left">退款明细</Divider>
          <Table columns={record_columns} dataSource={refundOrder ? refundOrder.children : null} /> */}
          <Divider orientation="left">审核说明</Divider>
          <Descriptions.Item>
            <Input onChange={handleRemark} placeholder="请输入审核备注" />
          </Descriptions.Item>
        </div>
      </CreateForm>
      <CreateForm
        title={'订单详情'}
        width={1300}
        onCancel={() => setOrder(false)}
        modalVisible={order}
        btn_view={null}
      >
        <OrderCommon
          payOrderValues={payOrderValues}
          refund={null}
        />
      </CreateForm>
      <CreateForm
        title={'会员活动详情'}
        width={1300}
        onCancel={() => setMemberActivity(false)}
        modalVisible={memberActivity}
        btn_view={null}
      >
        <Table dataSource={memberActivityList} columns={activityColumns} />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
